package com.partner.druidfilter;

import com.partner.druidfilter.model.Coffee;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@SpringBootApplication
@Slf4j
public class Druidfilter2Application implements ApplicationRunner {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public static void main(String[] args) {
        SpringApplication.run(Druidfilter2Application.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {

        ResultSetExtractor<List<Coffee>> resultSetExtractor = new ResultSetExtractor<>() {

            @Override
            public List<Coffee> extractData(ResultSet rs) throws SQLException, DataAccessException {
                List<Coffee> list = new ArrayList<>();
                while (rs.next()) {
                    Coffee coffee = new Coffee();
                    coffee.setId(rs.getLong("id"));
                    coffee.setName(rs.getString("name"));
                    coffee.setPrice(Money.of(CurrencyUnit.of("CNY"), rs.getLong("price") / 100.0));
                    coffee.setCreateTime(new Date(rs.getDate("create_time").getTime()));
                    coffee.setUpdateTime(new Date(rs.getDate("update_time").getTime()));
                    list.add(coffee);
                }
                return list;
            }
        };

        List<Coffee> list = jdbcTemplate.query("select * from t_coffee", resultSetExtractor);
        list.forEach(x -> log.info("query coffee: {}", x));

        // sql拼接校验测试
//        jdbcTemplate.query("select * from t_coffee; select * from t_coffee", resultSetExtractor);
        // sql in校验测试
        jdbcTemplate.query("select * from t_coffee where name in ('1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11')", resultSetExtractor);

    }
}
